<template>
  <el-dialog
    title="坐标定位"
    :visible.sync="isMapList.isMap"
    :destroy-on-close="true"
    :before-close="resetFun"
    @open="createMap"
    custom-class="map-workbench-dialog-wc"
    :style="{ '--theme': $store.getters.themeColor }"
  >
    <div class="wrapper">
      <div class="search-input-mapol">
        <amapSeach
          :defaultPlace="defaultPlace"
          :placeData.sync="placeData"
          @setPoints="drawPointsMarker"
          ref="amapSeach"
          :default="placeData.formattedAddress"
        ></amapSeach>
      </div>
      <div id="map_container"></div>
      <mapol-zoom
        :autoWidth="false"
        v-if="getInstance()?.map.map"
        :height="68"
        :width="30"
        :position="[null, null, 45, 114]"
        :customStyle="customStyle"
        :colorStyle="wordStyle"
        :show="show"
        bgColor="blue"
        :vertical="true"
        :mapInstance="getInstance()?.map.map"
      ></mapol-zoom>
      <!--      <mapol-scale-line scale="0.8" :autoWidth="false" :width="90"  v-if="getInstance()?.map.map" :position="[null, null, 22, 24]" height="36" rulerHeight="3" :vertical="false"   radius="4" :map-instance="getInstance()?.map.map"></mapol-scale-line>-->
      <MapolLayerSwitcher
        :height="60"
        :width="80"
        :position="[null, null, 45, 20]"
        :activeMode.sync="activeMode"
        :modes="modes"
        rulerHeight="3"
        radius="4"
        :map="getInstance()?.map"
      ></MapolLayerSwitcher>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button
        :disabled="disabled"
        @click="submitFun"
        class="submitClass"
        type="primary"
        :loading="loading"
        >确 定</el-button
      >
      <el-button @click="resetFun">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import position from '@/assets/image/position.png'
import eventBus from "@/utils/event-bus";
import CTMap from "@ct/ct_map_ol";
import { poiContraryGeocodingQuery } from "@/api/modules/eventManagement/eventMapol.js";
import amapSeach from "./eventDialog/amap-seach";
import {
  MapolLayerSwitcher,
  MapolScaleLine,
  MapolZoom,
} from "@ct/ct_map_ol/components";
import { ScaleLine } from "ol/control";
import CTMapOl from "@ct/ct_map_ol";
import { getTwoPointAngle } from "@/utils/countAngleDistance";
export default {
  name: "eventJudgeMapol",
  props: {
    isMapList: {
      type: Object,
      default: function () {
        return {};
      },
    },
    orderData: {
      type: Object,
      default: function () {
        return {};
      },
    },
    isAdd: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // map:null,
      // iconVector:null,
      // view:null,
      map: {},
      getInstance: () => {}, // 闭包函数，内部存放地图相关实例
      activeMode: "basic", // 切换地图组件默认样式
      modes: ["basic", "satellite"], // 切换地图组件列表样式
      placeData: {},
      addressData: {},
      loading: false,
      customStyle: {
        background: "transparent",
      },
      show: true,
      wordStyle: {
        "font-size": "14px",
        color: "#E4E7C1",
      },
      disabled: false,
      showLine: false,
      defaultPlace: null,
    };
  },
  components: {
    MapolLayerSwitcher,
    MapolScaleLine,
    amapSeach,
    MapolZoom,
  },
  methods: {
    submitFun() {
      console.log(this.placeData, this.addressData, "place,address");
      this.loading = true;
      this.addressData.countyCode = this.addressData.district =
        this.placeData.countyCode;
      this.addressData.cityCode = this.addressData.city =
        this.placeData.cityCode;
      this.addressData.provinceCode = this.addressData.province =
        this.placeData.provinceCode;
      this.addressData.townCode = this.placeData.townCode;
      this.addressData.latitude = Number(this.placeData.lat);
      this.addressData.longitude = Number(this.placeData.lon);
      if (this.isAdd) {
        this.addressData.address = this.placeData.address.split(
          this.placeData.town
        )[1];
        if (!this.addressData.address) {
          this.addressData.address =
            this.placeData.pois[0]?.name || this.placeData.address;
        }
      } else {
        this.addressData.address = this.placeData.address;
      }
      let getDistance = CTMap.sphere.getDistance;
      this.getInstance = () => {};
      // 告警来源为AI或者摄像机告警的时候计算水平角和俯仰角
      if (
        this.orderData.warningSource === "1" ||
        this.orderData.warningSource === "4"
      ) {
        const videoLngLat = [
          this.orderData.videoLongitude,
          this.orderData.videoLatitude,
        ];
        const alarmLngLat = [
          this.addressData.longitude,
          this.addressData.latitude,
        ];
        const distance = this.getDistanceByLatLng(videoLngLat, alarmLngLat, 5);
        const devicePitch =
          -1 *
          Math.abs(
            (Math.atan(this.orderData.height / (distance * 1000)) * 180) /
              Math.PI
          ).toFixed(2);
        this.addressData.horizontalAngles = this.getHorizontalAngle(
          videoLngLat,
          alarmLngLat,
          2
        ); // 水平角
        const angle = getTwoPointAngle(
          [this.orderData.videoLongitude, this.orderData.videoLatitude],
          [this.addressData.longitude, this.addressData.latitude],
          getDistance
        );
        this.addressData.devicePitch = devicePitch; // 俯仰角
        this.$set(this.orderData, "devicePitch", devicePitch);
        this.$set(this.orderData, "deviceHorizontal", angle);
      }

      // 处理是否修改了网格信息
      this.$emit("isMapCancelFun", this.addressData, getDistance);
      // this.getInstance().map.map.dispose();
      document.querySelector(".search-box-wrapper input").value = ""; //清空搜索
    },
    resetFun() {
      this.getInstance().map.map.dispose();
      this.getInstance = () => {};
      this.$emit("isMapCancelFun", false);
    },
    // 地图初始化
    mapInit() {
      let map = new CTMap.extend.InitMap({
        domId: "map_container",
        maxZoom: 18,
        minZoom: 3,
        zoom: 15,
        center: CTMap.extend.formatLayer.transCoordinate([116.39, 39.91]),
        tile: "vector",
      });
      this.addScaleLine(map.map, "demarcate-scaleLine", 88);
      let view = map.map.getView();
      //创建icon矢量容器
      let iconVector = new CTMap.source.Vector();
      //创建icon图层
      let iconLayer = new CTMap.layer.Vector({
        source: iconVector,
      });
      //将图层添加到地图上
      map.map.addLayer(iconLayer);
      return () => {
        return {
          map,
          iconVector,
          view,
        };
      };
    },
    /**
     * 地图事件监听
     */
    mapEvent() {
      this.getInstance().map.map.on("singleclick", (e) => {
        // e.coordinate 坐标
        // this.getInstance().view.animate({center:e.coordinate,duration:this.duration}); // 点位居中
        if (this.$refs.amapSeach) {
          this.$refs.amapSeach.showList = false;
        }

        this.drawPointsMarker(e.coordinate);
      });
    },
    /**
     * 绘制点位
     * @param {Array} coordinate 坐标
     */
    drawPointsMarker(coordinate, flag) {
      const view = this.getInstance().map.map.getView();
      this.getInstance().iconVector.clear(); //每次先清空容器
      let iconFeature = this.setPoints(coordinate);
      this.getInstance().iconVector.addFeature(iconFeature); //将创建好的feature放入到容器中
      setTimeout(() => {
        view.animate({ center: coordinate, duration: flag ? 0 : 2000 }); // 点位居中
      }, 17);
      // 获取标记feature的坐标
      let Features = this.getInstance().iconVector.getFeatures();
      if (Features && Features.length) {
        const local = CTMap.extend.formatLayer.transCooordinateFromOpenlayer(
          Features[0].values_.myCoordinate
        );
        let params = {
          location: local.join(","),
        };
        this.defaultPlace = local;
        this.disabled = true;
        poiContraryGeocodingQuery(params)
          .then((res) => {
            this.disabled = false;
            this.placeData = res.data[0].region;
            this.placeData.address = res.data[0].address;
            this.placeData.lon = local[0];
            this.placeData.lat = local[1];
            this.placeData.pois = res.data[0].pois;
            this.$refs.amapSeach.keyword = this.placeData.address;
          })
          .catch((e) => {
            this.disabled = false;
          });
        // CTMap.api.codeToAdress(params).then(res => {
        //   let obj = res.data;
        // });
      }
    },
    /**
     * 设置点标记样式
     * @param { Array } coordinate 坐标点位
     */
    setPoints(coordinate) {
      //创建标记feature   自定义myCoordinate属性，用于获取点标记的坐标值
      let iconFeature = new CTMap.Feature({
        type: "icon",
        geometry: new CTMap.geom.Point(coordinate),
        myCoordinate: coordinate,
      });
      let poiStyle = new CTMap.style.Style({
        image: new CTMap.style.Icon({
          src: position, //图标路径
          anchor: [0.5, 1],
        }),
      });
      iconFeature.setStyle(poiStyle);
      return iconFeature;
    },
    addScaleLine(map, className, maxWidth, divId) {
      let option = {
        className: className,
        units: "metric",
      };
      if (maxWidth) {
        option.maxWidth = maxWidth;
      }
      if (divId) {
        option.target = document.getElementById(divId);
      }
      let scaleLine = new ScaleLine(option);
      map.addControl(scaleLine);
      return scaleLine;
    },
    createMap() {
      this.$nextTick(() => {
        this.loading = false;
        this.getInstance = this.mapInit(); // 闭包赋值
        this.activeMode = "basic";
        this.mapEvent();
        if (!this.isAdd) {
          this.defaultPlace = [
            Number(this.isMapList.longitude),
            Number(this.isMapList.latitude),
          ];
          this.$nextTick(() => {
            this.drawPointsMarker(
              CTMap.extend.formatLayer.transCoordinate(this.defaultPlace),
              true
            );
          });
        } else {
          if (this.isMapList.lat) {
            this.defaultPlace = [
              Number(this.isMapList.lng),
              Number(this.isMapList.lat),
            ];
            this.drawPointsMarker(
              CTMap.extend.formatLayer.transCoordinate(this.defaultPlace)
            );
          } else {
            let center = this.getInstance().map.map.getView().getCenter();
            this.drawPointsMarker(center);
            this.defaultPlace =
              CTMap.extend.formatLayer.transCooordinateFromOpenlayer(center);
          }
        }
      });
    },
    /**
     * 计算两点间距离
     * @param start     开始点
     * @param end       结束点
     * @param num       保留小数点后几位
     * @returns {*}     两点间距离
     */
    getDistanceByLatLng(start, end, num) {
      let distance = CTMapOl.turf.distance(start, end);
      return distance.toFixed(num);
    },
    /**
     * 计算水平方位角
     * @param start       开始点
     * @param end         结束点
     * @param num         保留小数点后几位
     * @returns {*}       两点恒向线夹角
     */
    getHorizontalAngle(start, end, num) {
      let angle = CTMapOl.turf.rhumbBearing(start, end);
      return angle >= 0 ? angle.toFixed(num) : (angle + 360).toFixed(num);
    },
  },
  beforeDestroy() {
    this.getInstance = null;
  },
};
</script>

<style scoped lang="scss">
.wrapper {
  height: 500px;
  width: 100%;
  position: relative;
}
#map_container {
  height: 100%;
  width: 100%;
}
.search-input-mapol {
  position: relative;
}
/deep/.el-button.el-button--small {
  height: 32px;
}
</style>
<style lang="scss">
.map-workbench-dialog-wc {
  .ct-mapol-layer-switcher {
    z-index: 1 !important;
  }
  .scalebox {
    background: #fff;
  }
  .ct-mapol-layer-switcher__container {
    padding: 4px 0 !important;
    margin-left: 4px;
  }
  .ct-mapol-zoom {
    z-index: 1 !important;
    background: #fff !important;
  }
  .ct-mapol-zoom__label {
    color: #172537 !important;
    font-size: 12px !important;
    padding-top: 2px;
  }
  #scalebox {
    background: #fff;
    width: 100%;
    .ctfont {
      font-weight: 500;
    }
  }
  .demarcate-scaleLine {
    position: absolute;
    left: 20px;
    bottom: 15px;
    background: #ffffff;
    box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.15);
    border-radius: 4px;
    padding: 0 10px;
    &:before {
      content: "";
      width: 2px;
      height: 6px;
      pointer-events: none;
      position: absolute;
      left: 9px;
      top: 3px;
      background: #172537;
    }
    &:after {
      content: "";
      width: 2px;
      height: 6px;
      pointer-events: none;
      position: absolute;
      right: 9px;
      top: 3px;
      background: #172537;
    }
    .demarcate-scaleLine-inner {
      margin-top: 5px;
      margin-bottom: 3px;
      padding-top: 2px;
      border-top: 2px solid #172537;
      color: #172537;
      font-size: 10px;
      text-align: center;
      transition: all 0.25s;
      will-change: contents, width;
    }
  }
}
</style>
